class TriggersController < ApplicationController
	before_filter :login_required
    def index
    	@triggers = Trigger.find(	:all,
    					:conditions => "user_id = '#{current_user.id}'")
	end
	def create
	@trigger = Trigger.new(params[:trigger])
	stock = Stock.find(@trigger.stock_id)
	if @trigger.action == "buy" && @trigger.price*@trigger.quantity+brokerage(@trigger.price*@trigger.quantity) > current_user.cash 
			flash[:notice] = 'Trigger Unsuccessful! You dont have that much cash!'
			redirect_to(:controller => 'market')
	elsif @trigger.action == "sell" && Ownership.owns(current_user.id, @trigger.stock_id) < @trigger.quantity
			flash[:notice] = 'Trigger Unsuccessful! You dont have that much stock!'
			redirect_to(:controller => 'market')
	elsif @trigger.price < (stock.days_opening*85)/100 ||  @trigger.price > (stock.days_opening*115)/100
			flash[:notice] = 'Trigger Unsuccessful! More than 15% of movement not allowed!!'
                        redirect_to(:controller => 'market')
	else
      if @trigger.save!
        flash[:notice] = 'Trigger was successfully created.'
        if Flag.open?
        	engine
        end
        redirect_to(:controller => 'triggers')
      else
        flash[:notice] = 'Invalid Data!'
		redirect_to(:controller => 'market')
      end
	end
	end
	def delete
		@trigger = Trigger.find(params[:id])
    	@trigger.destroy
    	flash[:notice] = 'Trigger deleted!.'
    	redirect_to(:controller => 'triggers')
    	rescue
  			not_existing(id, 'trigger')
	end

end
